<!DOCTYPE html>
<html>

<head>
  <title>搜索自动补全示例</title>
  <style>
    .selected {
      background-color: lightgray;
    }
    input{
        font-size: 32px;
    }
  </style>
</head>

<body>
  <h1>搜索自动补全示例, 带键盘控制 , 输入 : app </h1>
  <input type="text" id="searchInput" placeholder="请输入搜索关键词">
  <ul id="suggestions"></ul>

  <script>
    // 模拟的搜索建议数据
    const suggestionsData = ['苹果', '香蕉', '橘子', '西瓜', '菠萝' , 'apple', 'demanding' , 'apple123'];

    // 获取输入框和建议列表元素
    const searchInput = document.getElementById('searchInput');
    const suggestionsList = document.getElementById('suggestions');

    let selectedIndex = -1; // 当前选中建议的索引

    // 监听输入框的输入事件
    searchInput.addEventListener('input', () => {
      const inputValue = searchInput.value.trim();
      suggestionsList.innerHTML = '';
      selectedIndex = -1;

      if (inputValue !== '') {
        const filteredSuggestions = getSuggestions(inputValue);

        filteredSuggestions.forEach((suggestion, index) => {
          const li = document.createElement('li');
          li.textContent = suggestion;
          suggestionsList.appendChild(li);

          li.addEventListener('click', () => {
            selectSuggestion(index);
          });
        });
      }
    });

    // 监听键盘按键事件
    searchInput.addEventListener('keydown', (event) => {
      const suggestions = suggestionsList.getElementsByTagName('li');

      if (event.key === 'ArrowUp') {
        event.preventDefault();
        if (selectedIndex > 0) {
          selectedIndex--;
          updateSelectedSuggestion(suggestions);
        }
      } else if (event.key === 'ArrowDown') {
        event.preventDefault();
        if (selectedIndex < suggestions.length - 1) {
          selectedIndex++;
          updateSelectedSuggestion(suggestions);
        }
      } else if (event.key === 'Enter' && selectedIndex !== -1) {
        event.preventDefault();
        selectSuggestion(selectedIndex);
      }
    });

    // 根据输入值获取匹配的建议结果
    function getSuggestions(input) {
      return suggestionsData.filter((suggestion) =>
        suggestion.toLowerCase().startsWith(input.toLowerCase())
      );
    }

    // 更新选中项的样式
    function updateSelectedSuggestion(suggestions) {
      for (let i = 0; i < suggestions.length; i++) {
        const suggestion = suggestions[i];
        if (i === selectedIndex) {
          suggestion.classList.add('selected');
          console.log(suggestion.innerHTML);
          searchInput.value = suggestion.innerHTML;
        } else {
          suggestion.classList.remove('selected');
        }
      }
    }

    // 选择建议并填充到输入框
    function selectSuggestion(index) {
      const selectedSuggestion = suggestionsList.getElementsByTagName('li')[index];
      if (selectedSuggestion) {
        searchInput.value = selectedSuggestion.textContent;
        suggestionsList.innerHTML = '';
        selectedIndex = -1;
      }
    }
  </script>
</body>

</html>
